#include <cstddef>

struct ListNode {
    int val;
    ListNode *next;

    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if (head == nullptr || head->next == nullptr)return nullptr;
        for (int i = 0; i < 10001; ++i) {
            if (head->val == 100001) return head;
            head->val = 100001;
            head = head->next;
        }
        return nullptr;
    }
};